//
//  AppMiddleAlertView.swift
//  LeTu
//
//  Created by g1 on 2023/12/17.
//

import UIKit

class AppMiddleAlertView: UIView {

    private let rootView: UIWindow? = AppThemeManager.keyWindow()
    private var backgroundView: UIView = UIView()
    
    private var agreeHolder: (() -> Void)?
    private var cancelHolder: (() -> Void)?
    
    init(title: String, content: String, leftTitle: String, rightTitle: String, agreeHolder: @escaping () -> Void, cancelHolder: @escaping () -> Void) {
        
        super.init(frame: .zero)
        
        self.agreeHolder = agreeHolder
        self.cancelHolder = cancelHolder
        
        guard rootView != nil else { return }
        configUI()
        
        titleLabel.text = title
        contentLabel.text = content
        cancelBtn.setTitle(leftTitle, for: .normal)
        agreeBtn.setTitle(rightTitle, for: .normal)
    
    }
    
    // MARK: - configUI
    func configUI() {
        
        guard let rootView = rootView else { return }
        
        // 防止多个 AlertView 重复显示
        if rootView.subviews.filter({ $0.isKind(of: AppMiddleAlertView.self) }).count > 0 { return }
                
        backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        
        rootView.addSubview(backgroundView)
        rootView.addSubview(self)
        addSubview(backView)
        backView.addSubview(titleLabel)
        backView.addSubview(contentLabel)
        backView.addSubview(cancelBtn)
        backView.addSubview(agreeBtn)
        
        loadLayout()
        rootView.layoutIfNeeded()

    }
    func loadLayout() {
        
        guard let rootView = rootView else { return }
        
        backgroundView.snp.makeConstraints { (make) in
            make.edges.equalTo(rootView)
        }
        self.snp.makeConstraints { make in
            make.edges.equalTo(rootView)
        }
        backView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(screenFixationWidth-120)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.right.equalTo(-22)
            make.top.equalTo(24)
            make.height.equalTo(20)
        }
        contentLabel.snp.makeConstraints { make in
            make.left.right.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
        }
        cancelBtn.snp.makeConstraints { make in
            make.top.equalTo(contentLabel.snp.bottom).offset(30)
            make.left.equalTo(28)
            make.width.equalToSuperview().multipliedBy(0.5).offset(-28-6)
            make.height.equalTo(40)
            make.bottom.equalTo(-28)
        }
        agreeBtn.snp.makeConstraints { make in
            make.right.equalTo(-32)
            make.centerY.width.height.equalTo(cancelBtn)
        }
        
        agreeBtn.addTarget(self, action: #selector(agreeAction), for: .touchUpInside)
        cancelBtn.addTarget(self, action: #selector(hideAction), for: .touchUpInside)
    }
    private lazy var backView: UIView = {
        let backView = UIView()
        backView.backgroundColor = .app_white
        backView.layer.cornerRadius = 18
        backView.clipsToBounds = true
        return backView
    }()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = kSetPingFangMedium(18)
        titleLabel.textAlignment = .center
        return titleLabel
    }()
    private lazy var contentLabel: UILabel = {
        let contentLabel = UILabel()
        contentLabel.font = kSetPingFangRegular(15)
        contentLabel.numberOfLines = 0
        contentLabel.textColor = .app_gray
        contentLabel.textAlignment = .center
        return contentLabel
    }()
    private lazy var cancelBtn: AppCustomButton = {
        let cancelBtn = AppCustomButton()
        cancelBtn.setTitle("取消".localized, for: .normal)
        cancelBtn.setTitleColor( .lightGray, for: .normal)
        cancelBtn.backgroundColor = .app_white
        cancelBtn.titleLabel?.font = kSetPingFangRegular(LanguageManager.shared.currentLanguage == .zh ? 16:14)
        cancelBtn.layer.cornerRadius = 20
        cancelBtn.layer.borderColor = UIColor.lightGray.cgColor
        cancelBtn.layer.borderWidth = .app_lineHieght
        return cancelBtn
    }()
    private lazy var agreeBtn: AppCustomButton = {
        let agreeBtn = AppCustomButton()
        agreeBtn.setTitleColor( .app_white, for: .normal)
        agreeBtn.backgroundColor = .app_themeColor
        agreeBtn.titleLabel?.font = kSetPingFangMedium(LanguageManager.shared.currentLanguage == .zh ? 16:14)
        agreeBtn.layer.cornerRadius = 20
        agreeBtn.layer.masksToBounds = true
        return agreeBtn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension AppMiddleAlertView {
    
    func show() {
        
        guard rootView != nil else { return }
        
        agreeBtn.layerCornerRadius(6)
        UIView.animate(withDuration: CGFloat.app_alertShowInterval-0.1) {
            self.backgroundView.backgroundColor = .app_customAlertBackgroundColor
        }
        UIView.animate(withDuration: CGFloat.app_alertShowInterval, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 20, options: UIView.AnimationOptions(rawValue: 0), animations: {
            self.backView.backgroundColor = UIColor.white.withAlphaComponent(1.0)
        })

    }
    
    @objc private func hideAction() {
        if let cancelHolder = cancelHolder {
            cancelHolder()
        }
        hide()
//        guard contentLabel.enabledTypes.count > 0 else { return }
//        exit(0)
    }
    
    @objc private func agreeAction() {
        guard let topHolder = agreeHolder else { return }
        topHolder()
        hide()
    }
    
    private func hide(completion: (() -> Void)? = nil) {
        
        UIView.animate(withDuration: CGFloat.app_alertHidenInterval, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions(rawValue: 0), animations: {
            self.titleLabel.alpha = 0
            self.backView.alpha = 0
            self.backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0)
        }) { finished in
            guard finished else { return }
            self.removeAppMiddleAlertView()
        }
        
    }
    func removeAppMiddleAlertView() {
        self.backgroundView.removeFromSuperview()
        self.removeFromSuperview()
    }
        
}

